var express = require('express');
var bodyParser = require('body-parser');
var url = require('url');
var path = require('path');
var fs = require('fs');
var httpProxy = require('http-proxy');
var mock = require('./mock/mockall');

var proxy = httpProxy.createProxyServer({ changeOrigin: true}); 
var root = path.join(__dirname, '/src');
var app = express();

app.use(express.static('.'));

// proxy.on('proxyReq', function (proxyReq, req, res) {
// 	console.log("on proxy req");
// 	if (req.body) {
// 		console.log(req.body);
// 		let bodyData = JSON.stringify(req.body)
// 		proxyReq.setHeader('Content-Type', 'application/json')
// 		proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
// 		// stream the content
// 		proxyReq.write(bodyData)
// 	}
// });
/*
app.all('/api/*', function (req, res, next) {
    var target = req.originalUrl.replace("/api/", "");
    // Change this API url to suit your project
    var url = `/${target}`;
    req.url = url;
    console.log(url);
    delete req.headers.host;
	// var restream = function (proxyReq, req, res, options) {
	// 	console.log("on proxy req");
	// 	if (req.body) {
	// 		console.log(req.body);
	//
	// 		let bodyData = JSON.stringify(req.body)
	// 		// incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
	// 		proxyReq.setHeader('Content-Type', 'application/json')
	// 		proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData))
	// 		// stream the content
	// 		proxyReq.write(bodyData)
	// 	}
	// };
    proxy.web(req, res, { target: 'http://localhost:3300', changeOrigin: true }); 
})
*/

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(mock);


app.get('/', function(req,res) {
	var file = path.join(__dirname, "public/index.html");
	
	fs.readFile(file, function(err, data){
		if(err){
			res.writeHeader(404, {
				'content-type' : 'text/html;charset="utf-8"'
			});
			res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
			res.end();
		} else {
			res.writeHeader(200, {
				'content-type' : 'text/html;charset="utf-8"'
			});
			res.write(data);
			res.end();
		}
	});
});

var server = app.listen(3000, function () {
	var host = server.address().address;
	var port = server.address().port;

	console.log('Example app listening at http://%s:%s', host, port);
});

/*
var io = require('socket.io')(server, {'transports': ['websocket', 'polling']});

var fileList = [];

findAllFile(root);

function findAllFile(filePath){
    let files = fs.readdirSync(filePath);
    files.forEach(function (item, index) {
        let fPath = path.join(filePath,item);
        let stat = fs.statSync(fPath);
        if(stat.isDirectory() === true) {
            findAllFile(fPath);
        }
        if (stat.isFile() === true) { 
          fileList.push(fPath);
        }
    });
}

createWatcher('reload');

function createWatcher(event) {
	fileList.forEach(function(file) {
		var absolute = file;
		fs.watchFile(absolute, function (curr, prev) {
			if (curr.mtime !== prev.mtime) {
				console.log(absolute + ' be modified.');
				io.sockets.emit(event, file.substr(root.length));
 		        wss.clients.forEach(function each(client) {
              	  	client.send("reload");
			  	})
			}
		});		
	})
}
*/
